<template>
  <div class="equipment-record-container">
    <!-- 查询条件卡片 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="from" class="search-form">
        <!-- 设备类型选择 -->
        <el-form-item label="设备类型">
          <el-select v-model="from.region" placeholder="请选择" style="width: 140px;" clearable>
            <el-option label="电声诊断仪器" value="电声诊断仪器" />
            <el-option label="心电图显示频" value="心电图显示频" />
          </el-select>
        </el-form-item>
        <!-- 状态选择 -->
        <el-form-item label="状态">
          <el-select v-model="from.state" placeholder="请选择" style="width: 100px;" clearable>
            <el-option label="未归还" value="1" />
            <el-option label="归还" value="2" />
          </el-select>
        </el-form-item>
        <!-- 借用日期选择 -->
        <el-form-item label="借用日期">
          <el-date-picker v-model="from.borrowDate" type="date" placeholder="请选择" style="width: 120px;" clearable />
        </el-form-item>
        <!-- 设备编号输入 -->
        <el-form-item label="设备编号">
          <el-input v-model="from.equipmentNo" placeholder="请输入" style="width: 100px;" clearable />
        </el-form-item>
        <!-- 借用人输入 -->
        <el-form-item label="借用人">
          <el-input v-model="from.borrower" placeholder="请输入" style="width: 100px;" clearable />
        </el-form-item>
        <!-- 归还人输入 -->
        <el-form-item label="归还人">
          <el-input v-model="from.returnUser" placeholder="请输入" style="width: 100px;" clearable />
        </el-form-item>
        <!-- 查询、新增按钮 -->
        <el-form-item class="search-buttons">
          <el-button type="primary" @click="onSubmit()" icon="Search">查询</el-button>
          <el-button type="success" @click="openadd()" icon="Plus">新增</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 设备外借记录表格卡片 -->
    <el-card class="table-card">
      <el-table :data="tableData" border style="width: 100%" :header-cell-style="headerCellStyle" :cell-style="cellStyle" stripe>
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="equipmentType" label="设备类型" width="180" />
        <el-table-column prop="equipmentNo" label="设备编号" width="180" />
        <el-table-column prop="borrower" label="借用人" width="180" />
        <el-table-column prop="borrowDate" label="借用日期" width="180" />
        <el-table-column prop="currentUser" label="当前使用人" width="180" />
        <el-table-column prop="returnUser" label="归还人" width="180" />
        <el-table-column prop="returnDate" label="归还日期" width="180" />
        <el-table-column prop="state" label="状态" align="center">
          <template v-slot="scope">
            <!-- 状态标签，未归还可点击归还，归还为绿色 -->
            <el-tag type="danger" v-if="scope.row.state == 1" effect="dark" @click="openstate(scope.row)" class="clickable-tag">未归还</el-tag>
            <el-tag  v-if="scope.row.state == 2"   :disabled="true" >归还</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pageing.index" v-model:page-size="pageing.size" :page-sizes="[2, 3, 4, 10, 20]"
          :background="true" layout="total, sizes, prev, pager, next, jumper" :total="pageing.total" />
      </div>
    </el-card>

    <!-- 新增设备外借弹窗 -->
    <el-dialog v-model="logic.isadd" width="550" title="添加设备外借" destroy-on-close center custom-class="custom-dialog">
      <el-form :model="form" ref="ruleFormRef" :rules="rules" label-width="100px" class="dialog-form">
        <el-form-item label="设备类型" prop="equipmentType">
          <el-select v-model="form.equipmentType" placeholder="请选择" clearable>
            <el-option label="电声诊断仪器" value="电声诊断仪器" />
            <el-option label="心电图显示频" value="心电图显示频" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备编号" prop="equipmentNo">
          <el-select v-model="form.equipmentNo" placeholder="请选择" clearable>
            <el-option label="SB001" value="SB001" />
            <el-option label="SB002" value="SB002" />
            <el-option label="SB003" value="SB003" />
          </el-select>
        </el-form-item>
        <el-form-item label="借用人" prop="borrower">
          <el-input v-model="form.borrower" autocomplete="off" />
        </el-form-item>
        <el-form-item label="借用日期" prop="borrowDate">
          <el-date-picker v-model="form.borrowDate" type="date" placeholder="请选择" clearable />
        </el-form-item>
        <el-form-item label="当前使用人" prop="currentUser">
          <el-input v-model="form.currentUser" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close()" icon="Close">取消</el-button>
          <el-button type="primary" @click="add()" icon="Check">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 归还设备外借弹窗 -->
    <el-dialog v-model="logic.isstate" width="550" title="归还设备外借" destroy-on-close center custom-class="custom-dialog">
      <el-form :model="from1" ref="from1FormRef" :rules="from1Rules" label-width="100px" class="dialog-form">
        <el-form-item label="归还人" prop="returnUser">
          <el-input v-model="from1.returnUser" autocomplete="off" />
        </el-form-item>
        <el-form-item label="归还日期" prop="returnDate">
          <el-date-picker v-model="from1.returnDate" type="date" placeholder="请选择" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close()" icon="Close">取消</el-button>
          <el-button type="primary" @click="upd()" icon="Check">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
import { reactive, ref, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()

// 弹框控制逻辑
const logic = reactive({
  isadd: false, // 新增弹窗
  isstate: false // 归还弹窗
})
// 查询条件表单
const from = reactive({
  equipmentType: "",
  equipmentNo: "",
  borrower: "",
  borrowDate: "",
  currentUser: "",
  returnUser: "",
  returnDate: "",
  state: "",
})
// 分页信息
const pageing = reactive({
  index: 1, // 当前页
  size: 2,  // 每页条数
  total: 0  // 总条数
})
// 监听分页变化，自动刷新表格
watch(pageing, () => {
  gettableData()
})
// 表格数据
const tableData = ref([])
// 获取表格数据方法
const gettableData = () => {
  console.log("222", from)
  console.log("333", pageing)
  // 调用后端接口获取设备外借记录
  proxy.http.get("api/EquipmentController/GetEquipmentRecord?equipmentType=" + from.equipmentType + "&state=" + from.state + "&borrowDate=" + from.borrowDate + "&equipmentNo=" + from.equipmentNo + "&borrower=" + from.borrower + "&returnUser=" + from.returnUser + "&pageIndex=" + pageing.index + "&pageSize=" + pageing.size).then(res => {
    console.log("111", res.data)
    tableData.value = res.data.rows
    pageing.total = res.data.total
  })
}
// 查询按钮事件
const onSubmit = () => {
  gettableData()
}
// 页面挂载时自动加载表格数据
onMounted(() => {
  gettableData()
})
// 新增表单model
const form = reactive({
  equipmentType: "",
  equipmentNo: "",
  borrower: "",
  borrowDate: "",
  currentUser: "",
  returnUser: "",
  returnDate: "",
  state: '',
})
// 新增按钮事件，打开新增弹窗并重置表单
const openadd = () => {
  logic.isadd = true
  form.equipmentType = ""
  form.equipmentNo = ""
  form.borrower = ""
  form.borrowDate = ""
  form.currentUser = ""
  form.returnUser = ""
  form.returnDate = ""
  form.state = ""
}
// 表单校验ref
const ruleFormRef = ref()
const searchFormRef = ref()
const from1FormRef = ref()

// 新增表单校验规则
const rules = {
  equipmentType: [
    { required: true, message: '请选择设备类型', trigger: 'change' }
  ],
  equipmentNo: [
    { required: true, message: '请选择设备编号', trigger: 'change' }
  ],
  borrower: [
    { required: true, message: '请输入借用人', trigger: 'blur' }
  ],
  borrowDate: [
    { required: true, message: '请选择借用日期', trigger: 'change' }
  ],
  currentUser: [
    { required: true, message: '请输入当前使用人', trigger: 'blur' }
  ]
}
// 归还表单校验规则
const from1Rules = {
  returnUser: [
    { required: true, message: '请输入归还人', trigger: 'blur' }
  ],
  returnDate: [
    {
      validator: (rule, value, callback) => {
        if (value && from1.borrowDate) {
          const returnDateStr = value instanceof Date ?
            value.toISOString().split('T')[0] :
            String(value).split('T')[0];
          const borrowDateStr = from1.borrowDate instanceof Date ?
            from1.borrowDate.toISOString().split('T')[0] :
            String(from1.borrowDate).split('T')[0];
          if (returnDateStr <= borrowDateStr) {
            callback(new Error('归还日期必须大于借用日期'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
}
// 新增提交方法
const add = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      // 调用后端接口新增设备外借记录
      const response = await proxy.http.post("api/EquipmentController/AddEquipmentRecord", form)
      if (response > 0) {
        ElMessage.success("添加成功")
        logic.isadd = false
        gettableData()
      } else {
        ElMessage.error("添加失败")
      }
    }
  })
}
// 归还弹窗model
const from1 = reactive({
  id: "",
  equipmentType: "",
  equipmentNo: "",
  borrower: "",
  borrowDate: "",
  currentUser: "",
  returnUser: "",
  returnDate: "",
  state: '',
})
// 打开归还弹窗并填充数据
const openstate = (row) => {
  logic.isstate = true
  from1.id = row.id
  from1.equipmentType = row.equipmentType
  from1.equipmentNo = row.equipmentNo
  from1.borrower = row.borrower
  from1.borrowDate = row.borrowDate
  from1.currentUser = row.currentUser
  from1.returnUser = ""
  from1.returnDate = ""
  from1.state = row.state
}
// 归还提交方法
const upd = async () => {
  if (!from1FormRef.value) return
  await from1FormRef.value.validate(async (valid) => {
    if (valid) {
      // 处理日期格式
      if (from1.returnDate) {
        if (typeof from1.returnDate === 'object' && from1.returnDate instanceof Date) {
          from1.returnDate = from1.returnDate.toISOString().split('T')[0];
        } else if (typeof from1.returnDate === 'string' && from1.returnDate.includes('T')) {
          from1.returnDate = from1.returnDate.split('T')[0];
        }
      }
      console.log("要提交的数据", from1);
      // 调用后端接口归还设备
      const response = await proxy.http.post("api/EquipmentController/UpdEquipmentRecord", from1)
      if (response > 0) {
        ElMessage.success("归还成功")
        gettableData()
        logic.isstate = false
      } else {
        ElMessage.error("归还失败")
      }
    }
  })
}
// 关闭弹窗
const close = () => {
  logic.isadd = false
  logic.isstate = false
}
// 表格表头样式
const headerCellStyle = {
  background: '#f5f7fa',
  color: '#606266',
  fontWeight: 'bold',
  textAlign: 'center'
}
// 表格单元格样式
const cellStyle = {
  textAlign: 'center'
}
</script>

<style scoped>
.equipment-record-container {
  padding: 16px;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.search-buttons {
  margin-left: auto;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-form {
  margin: 20px;
  padding: 10px;
}

.dialog-form .el-form-item {
  margin-bottom: 22px;
}

.dialog-form .el-select,
.dialog-form .el-date-picker,
.dialog-form .el-input {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.dialog-footer .el-button {
  min-width: 120px;
  margin: 0 15px;
  padding: 12px 20px;
  border-radius: 4px;
  font-size: 14px;
}

.clickable-tag {
  cursor: pointer;
}

.clickable-tag:hover {
  opacity: 0.8;
}

:deep(.el-dialog__header) {
  margin-bottom: 10px;
  font-weight: bold;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 15px;
  text-align: center;
}

:deep(.el-dialog__body) {
  padding: 15px 25px;
}

:deep(.custom-dialog) {
  border-radius: 8px;
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  color: #303133;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-table th) {
  font-weight: bold;
  padding: 12px 0;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-button) {
  padding: 10px 20px;
}
</style>